package com.yanqu.road.server.manager.monopolymarket;

import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.enums.eMonopolyMarketResType;
import com.yanqu.road.entity.monopolymarket.MonopolyMarket;
import com.yanqu.road.entity.monopolymarket.config.MonopolyMarketResConfigData;
import com.yanqu.road.entity.monopolymarket.fortress.*;
import com.yanqu.road.entity.monopolymarket.office.log.MonopolyMarketFortressSettlementLogData;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.logic.bussiness.monopolymarket.MonopolyMarketBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.monopolymarket.MonopolyMarketProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.config.PatronsMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.MonopolyMarketCommonMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 边关要塞
 * @Author cwq
 * @Data 2021/10/13 18:30
 */
public class MonopolyMarketFortressMgr {

    public static Logger logger = LogManager.getLogger(MonopolyMarketFortressMgr.class.getName());

    /**
     * 要塞配置  k：id
     */
    public static Map<Integer, MonopolyMarketResConfigData> fortressConfigMap = new ConcurrentHashMap<>();

    /**
     * 每个玩家 可领取的采集奖励 集合
     */
    public static Map<Long, List<MonopolyMarketFortressRewardData>> userRewardMap = new ConcurrentHashMap<>();

    /**
     * 临时采集的奖励 入库用
     */
    public static List<MonopolyMarketFortressRewardData> tempRewardFinishList = new ArrayList<>();


    public static boolean reloadConfig(){
        Map<Integer, MonopolyMarketResConfigData> configMap = new ConcurrentHashMap<>();
        for (MonopolyMarketResConfigData item : MonopolyMarketMgr.resConfigList){
            if(item.getType() == eMonopolyMarketResType.FORTRESS.getValue()) {
                configMap.put(item.getId(), item);
            }
        }
        fortressConfigMap = configMap;
        return true;
    }

    public static void initFortress(MonopolyMarket monopolyMarket){
        // 检查上轮是否正常结束 如果没有 补发采集奖励
        checkNormalSettlement(monopolyMarket);

        // 加载本周边关要塞数据
        if(!MonopolyMarketCommonMgr.isFortressEnd(monopolyMarket)) {
            int weekId = MonopolyMarketCommonMgr.getMonopolyMarketWeekId();
            List<MonopolyMarketFortressUnionData> unionList = MonopolyMarketBussiness.getMonopolyMarketFortressUnionDataList(monopolyMarket.group.getGroupId(), weekId);
            for (MonopolyMarketFortressUnionData item : unionList) {
                MonopolyMarketFortressUnionInfo unionInfo = new MonopolyMarketFortressUnionInfo(item);
                monopolyMarket.monopolyMarketFortress.unionMap.put(item.getUnionId(), unionInfo);
            }
            List<MonopolyMarketFortressUserData> userDataList = MonopolyMarketBussiness.getMonopolyMarketFortressUserDataList(monopolyMarket.group.getGroupId(), weekId);
            for (MonopolyMarketFortressUserData item : userDataList) {
                monopolyMarket.monopolyMarketFortress.userMap.put(item.getUserId(), item);
                if (!StringUtils.isNullOrEmpty(item.getUnionId())) {
                    MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(item.getUnionId());
                    if (unionInfo == null) {
                        logger.error("存在 有的玩家没有对应的商会数据");
                        continue;
                    }
                    unionInfo.memberInfoMap.put(item.getUserId(), item);
                }
            }
            List<MonopolyMarketFortressRankData> list = MonopolyMarketBussiness.getMonopolyMarketFortressRankData(monopolyMarket.group.getGroupId(), weekId);
            for (MonopolyMarketFortressRankData item : list) {
                MonopolyMarketFortressCity city = getMonopolyMarketFortressCity(monopolyMarket, item.getFortressId(), true);
                MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(item.getUnionId());
                if(unionInfo == null){
                    logger.error("存在 有的排行榜 没有对应的商会数据");
                    continue;
                }
                if(!unionInfo.baseInfo.getIsDelete()){
                    city.rankMap.put(item.getUnionId(), item);
                    if(item.getTotalValue() > 0){
                        city.rankList.add(item);
                    }
                }
            }
            if(MonopolyMarketCommonMgr.isSettlementFortress() || MonopolyMarketCommonMgr.isCollectingFortress()){
                for (MonopolyMarketFortressCity item : monopolyMarket.monopolyMarketFortress.cityMap.values()){
                    sortMonopolyMarketFortressCity(item);
                }
            }
        }
    }

    public static void save(MonopolyMarket monopolyMarket){
        for (MonopolyMarketFortressUserData item : monopolyMarket.monopolyMarketFortress.userMap.values()){
            if (item.isUpdateOption()) {
                MonopolyMarketBussiness.updateMonopolyMarketFortressUserData(item);
            } else if (item.isInsertOption()) {
                MonopolyMarketBussiness.addMonopolyMarketFortressUserData(item);
            }
        }

        for (MonopolyMarketFortressUnionInfo item : monopolyMarket.monopolyMarketFortress.unionMap.values()){
            if (item.baseInfo.isUpdateOption()) {
                MonopolyMarketBussiness.updateMonopolyMarketFortressUnionData(item.baseInfo);
            } else if (item.baseInfo.isInsertOption()) {
                MonopolyMarketBussiness.addMonopolyMarketFortressUnionData(item.baseInfo);
            }
        }

        for (MonopolyMarketFortressCity item : monopolyMarket.monopolyMarketFortress.cityMap.values()){
            for (MonopolyMarketFortressRankData rankData : item.rankMap.values()){
                if (rankData.isUpdateOption()) {
                    MonopolyMarketBussiness.updateMonopolyMarketFortressRankData(rankData);
                } else if (rankData.isInsertOption()) {
                    MonopolyMarketBussiness.addMonopolyMarketFortressRankData(rankData);
                }
            }
        }
    }


    /**
     * 玩家进入要塞大厅
     * @return
     */
    public static MonopolyMarketProto.MonopolyMarketEnterFortressRespMsg.Builder enter(long serverId,String unionId,long userId){
        MonopolyMarketProto.MonopolyMarketEnterFortressRespMsg.Builder builder = MonopolyMarketProto.MonopolyMarketEnterFortressRespMsg.newBuilder();
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId,true);
        if(monopolyMarket == null){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        synchronized (monopolyMarket){
            unionId = getUserBelongUnionId(monopolyMarket, unionId,userId);
            for(MonopolyMarketFortressCity item : monopolyMarket.monopolyMarketFortress.cityMap.values()){
                // 获取自己联盟占领的信息
                MonopolyMarketFortressRankData rankInfo = getRankInfo(monopolyMarket,item,unionId,false);
                if(rankInfo != null && rankInfo.getTotalValue() > 0){
                    // 自己联盟派遣信息
                    MonopolyMarketProto.MonopolyMarketFortressUnionDispatchEntity.Builder unionDispatch = MonopolyMarketProto.MonopolyMarketFortressUnionDispatchEntity.newBuilder();
                    unionDispatch.setId(item.id);
                    // 玩家派遣的值
                    unionDispatch.setUnionTotalValue(rankInfo.getTotalValue());
                    // 联盟排名
                    if(MonopolyMarketCommonMgr.isCollectingFortress()){
                        unionDispatch.setRank(rankInfo.getRank());
                    }else {
                        unionDispatch.setRank(-1);
                    }
                    // 玩家派遣的值
                    unionDispatch.setValue(getUserDispatchValue(monopolyMarket,unionId,item.id,userId));
                    // 派遣人数
                    unionDispatch.setDispatchNum(getDispatchNum(monopolyMarket,unionId,item.id));
                    builder.addUnionDispatchInfo(unionDispatch);
                }
                if(item.rankList.size() != 0){
                    MonopolyMarketProto.MonopolyMarketFortressEntity.Builder fortressEntity = MonopolyMarketProto.MonopolyMarketFortressEntity.newBuilder();
                    fortressEntity.setId(item.id);
                    fortressEntity.setUnionNum(item.rankList.size());
                    if(MonopolyMarketCommonMgr.isCollectingFortress()){
                        // 下发城主信息
                        MonopolyMarketFortressRankData firstRankInfo = item.rankList.get(0);
                        if(firstRankInfo != null){
                            fortressEntity.setId(item.id);
                            fortressEntity.setUnionId(firstRankInfo.getUnionId());
                            fortressEntity.setUnionNum(item.rankList.size());
                            // 排名第一的联盟信息
                            MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(firstRankInfo.getUnionId());
                            if(unionInfo != null){
                                fortressEntity.setUnionBaseInfo(UnionBasePb.parseUnionBaseTempMsg(unionInfo.baseInfo.getUnionBaseInfo()));
                            }
                        }
                    }
                    builder.addFortressList(fortressEntity);
                }
            }
            builder.setMemberNum(getUnionMemberNum(monopolyMarket,unionId));
            builder.setFortressUnionId(unionId);
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 玩家进入要塞城池
     * @return
     */
    public static MonopolyMarketProto.MonopolyMarketEnterFortressCityRespMsg.Builder enterCity(long serverId,String unionId,long userId,int cityId,boolean isGetJoinUnion,boolean isGetCollectingUnion){
        MonopolyMarketProto.MonopolyMarketEnterFortressCityRespMsg.Builder builder = MonopolyMarketProto.MonopolyMarketEnterFortressCityRespMsg.newBuilder();
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId,true);
        if(monopolyMarket == null){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        synchronized (monopolyMarket){
            unionId = getUserBelongUnionId(monopolyMarket, unionId,userId);
            List<MonopolyMarketProto.MonopolyMarketFortressCityUserDispatchEntity> list = getMonopolyMarketFortressCityUserDispatchEntityList(monopolyMarket,unionId,cityId,userId);
            // 获取联盟里玩家派遣的记录
            builder.addAllUserList(list);
            MonopolyMarketFortressCity city = getMonopolyMarketFortressCity(monopolyMarket,cityId,false);
            // 获取参赛联盟信息
            if(city != null ){
                if(MonopolyMarketCommonMgr.isDispatchFortress() || MonopolyMarketCommonMgr.isSettlementFortress()){
                    for (MonopolyMarketFortressRankData item : city.rankMap.values()) {
                        if (item.getTotalValue() <= 0) {
                            continue;
                        }
                        MonopolyMarketFortressUnionInfo unionInfo = getMonopolyMarketFortressUnionInfo(monopolyMarket,item.getUnionId(),false);
                        if(unionInfo != null ){
                            builder.addJoinUnionNameList(unionInfo.baseInfo.getUnionBaseInfo().getUnionName());
                        }
                    }
                }
                if(MonopolyMarketCommonMgr.isCollectingFortress()){
                    if(isGetJoinUnion ){
                        for (MonopolyMarketFortressRankData item : city.rankList){
                            if(item.getTotalValue() <= 0){
                                continue;
                            }
                            MonopolyMarketProto.MonopolyMarketFortressJoinUnionEntity.Builder joinUnionEntity = MonopolyMarketProto.MonopolyMarketFortressJoinUnionEntity.newBuilder();
                            joinUnionEntity.setUnionId(item.getUnionId());
                            MonopolyMarketFortressUnionInfo fortressUnionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(item.getUnionId());
                            if(fortressUnionInfo != null){
                                joinUnionEntity.setUnionName(fortressUnionInfo.baseInfo.getUnionBaseInfo().getUnionName());
                            }
                            joinUnionEntity.setRank(item.getRank());
                            joinUnionEntity.setUnionTotalValue(item.getTotalValue());
                            builder.addJoinUnionList(joinUnionEntity);
                        }
                    }
                    if(isGetCollectingUnion ){
                        int collectUnionNum = getCollectUnionNum(cityId);
                        for (MonopolyMarketFortressRankData item : city.rankList) {
                            if(collectUnionNum-- <= 0){
                                break;
                            }
                            MonopolyMarketProto.MonopolyMarketFortressCollectingUnionEntity.Builder collectionUnionEntity = MonopolyMarketProto.MonopolyMarketFortressCollectingUnionEntity.newBuilder();
                            collectionUnionEntity.setUnionId(item.getUnionId());
                            MonopolyMarketFortressUnionInfo rankUnionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(item.getUnionId());
                            if(rankUnionInfo != null){
                                collectionUnionEntity.setUnionName(rankUnionInfo.baseInfo.getUnionBaseInfo().getUnionName());
                                collectionUnionEntity.setServerId(rankUnionInfo.baseInfo.getUnionBaseInfo().getServerId());
                                collectionUnionEntity.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(rankUnionInfo.baseInfo.getUnionBaseInfo()));
                            }
                            collectionUnionEntity.setRank(item.getRank());
                            builder.addCollectingUnionList(collectionUnionEntity);
                        }
                    }
                }
            }
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 派遣门客
     * @param serverId
     * @param unionId
     * @param userId
     */
    public static MonopolyMarketProto.MonopolyMarketFortressUnionDispatchToGameServerMsg.Builder dispatch(long serverId,String unionId,String unionName,long userId,int cityId,List<MonopolyMarketFortressPatronsDispatchInfo> dispatchInfoList ){
        MonopolyMarketProto.MonopolyMarketFortressUnionDispatchToGameServerMsg.Builder builder = MonopolyMarketProto.MonopolyMarketFortressUnionDispatchToGameServerMsg.newBuilder();
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId,true);
        if(monopolyMarket == null){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        synchronized (monopolyMarket){
            if(!MonopolyMarketCommonMgr.isSystemOpen(monopolyMarket.group, eMonopolyMarketResType.FORTRESS.getValue())){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_SYSTEM_NO_OPEN);
                return builder;
            }
            if(!MonopolyMarketCommonMgr.isDispatchFortress()){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_NO_IN_DISPATCH_PERIOD);
                return builder;
            }
            if(StringUtils.isNullOrEmpty(unionId)){
                builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
                return builder;
            }
            // 判断城池id 是否存在
            if(!fortressConfigMap.containsKey(cityId)){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_CITY_ID_NO_EXIST);
                return builder;
            }
            MonopolyMarketFortressUnionInfo unionInfo = MonopolyMarketFortressMgr.getMonopolyMarketFortressUnionInfo(monopolyMarket,unionId,true);
            if(unionInfo.baseInfo.getIsDelete()){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_CANNOT_DISPATCH);
                return builder;
            }
            if(!unionInfo.baseInfo.getUnionBaseInfo().getUnionName().equals(unionName)){
                unionInfo.baseInfo.getUnionBaseInfo().setUnionName(unionName);
            }
            // 派遣记录
            MonopolyMarketFortressUserData userData = MonopolyMarketFortressMgr.getMonopolyMarketFortressUserData(monopolyMarket,userId,unionId,true);
            Set<Integer> needRefreshRank = new HashSet<>();
            // 1先移除玩家该城池所有派遣门客
            List<MonopolyMarketFortressPatronsDispatchInfo> oldDispatchList = userData.getDispatchMap().remove(cityId);
            if(oldDispatchList != null && oldDispatchList.size() != 0){
                for (MonopolyMarketFortressPatronsDispatchInfo item : oldDispatchList){
                    userData.dispatchCityMap.remove(item.getId());
                }
                userData.setUpdateOption();
                needRefreshRank.add(cityId);
            }
            // 2移除要派遣门客原先的位置
            for(MonopolyMarketFortressPatronsDispatchInfo item : dispatchInfoList){
                // 所在城池id
                Integer id = userData.dispatchCityMap.remove(item.getId());
                if(id != null){
                    needRefreshRank.add(id);
                    List<MonopolyMarketFortressPatronsDispatchInfo> patronsDispatchInfoList = userData.getDispatchMap().get(id);
                    if(patronsDispatchInfoList != null){
                        Iterator<MonopolyMarketFortressPatronsDispatchInfo> iterator = patronsDispatchInfoList.iterator();
                        while (iterator.hasNext()){
                            MonopolyMarketFortressPatronsDispatchInfo info = iterator.next();
                            if(info.getId() == item.getId()){
                                iterator.remove();
                                break;
                            }
                        }
                    }
                }
            }
            if(dispatchInfoList.size() > 0){
                userData.getDispatchMap().put(cityId,dispatchInfoList);
                userData.setUpdateOption();
                for(MonopolyMarketFortressPatronsDispatchInfo item : dispatchInfoList){
                    userData.dispatchCityMap.put(item.getId(),cityId);
                }
                needRefreshRank.add(cityId);
            }
            needRefreshRank.forEach(e->{
                refreshRank(monopolyMarket,unionId,e,true);
            });

            // 同步该玩家派遣信息
            builder.addAllFortressDispatchList(MonopolyMarketFortressMgr.getMonopolyMarketFortressUserDispatchList(monopolyMarket,userId));

            // 日志
            List<MonopolyMarketFortressPatronsDispatchInfo> list = userData.getDispatchMap().get(cityId);
            StringBuilder patronsStr = new StringBuilder();
            if(list != null){
                for (MonopolyMarketFortressPatronsDispatchInfo item : list){
                    patronsStr.append(item.getId()).append(",");
                }
            }
            builder.setFortressId(cityId);
            builder.setEarn(getUserDispatchValue(monopolyMarket,unionId,cityId,userId));
            builder.setUnionEarn(getUnionDispatchValue(monopolyMarket,unionId,cityId));
            builder.setUnionId(unionId);
            builder.setPatronsStr(patronsStr.toString());
        }
        builder.setRet(0);
        return builder;
    }


    /**
     * 查看排行榜
     */
    public static MonopolyMarketProto.MonopolyMarketFortressGetRankRespMsg.Builder getRankList(long serverId, long userId, int cityId, boolean isGetRankList){
        MonopolyMarketProto.MonopolyMarketFortressGetRankRespMsg.Builder builder = MonopolyMarketProto.MonopolyMarketFortressGetRankRespMsg.newBuilder();
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId,true);
        if(monopolyMarket == null){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        synchronized (monopolyMarket){
            MonopolyMarketFortressCity city = getMonopolyMarketFortressCity(monopolyMarket,cityId,false);

            if(city != null) {
                String unionId = getUserBelongUnionId(monopolyMarket, "", userId);
                if (isGetRankList) {
                    int maxRank = getMaxRankReward(cityId);
                    for (MonopolyMarketFortressRankData item : city.rankList) {
                        if(item.getTotalValue() <= 0 || maxRank-- <= 0){
                            break;
                        }
                        // 只下发有资格领奖的联盟
                        MonopolyMarketProto.MonopolyMarketFortressUnionRankEntity.Builder unionRankEntity = MonopolyMarketProto.MonopolyMarketFortressUnionRankEntity.newBuilder();
                        unionRankEntity.setUnionId(item.getUnionId());
                        MonopolyMarketFortressUnionInfo rankUnionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(item.getUnionId());
                        if (rankUnionInfo != null) {
                            unionRankEntity.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(rankUnionInfo.baseInfo.getUnionBaseInfo()));
                        }
                        unionRankEntity.setTotalValue(item.getTotalValue());
                        unionRankEntity.setRank(item.getRank());
                        builder.addRankList(unionRankEntity);
                    }
                }
                MonopolyMarketFortressRankData rankInfo = getRankInfo(monopolyMarket, city, unionId, false);
                if (rankInfo != null) {
                    builder.setTotalValue(rankInfo.getTotalValue());
                    int maxRank = getMaxRankReward(cityId);
                    if(rankInfo.getRank() > maxRank){
                        builder.setRank(-1);
                    }else {
                        builder.setRank(rankInfo.getRank());
                        // 可领奖的排名
                        MonopolyMarketFortressRankReward rankReward = getRankReward(cityId, rankInfo.getRank());
                        if(rankReward != null){
                            MonopolyMarketFortressUserData marketFortressUserData = getMonopolyMarketFortressUserData(monopolyMarket, userId, unionId, true);
                            if (!marketFortressUserData.getReceivedIdList().contains(cityId) ) {
                                builder.setIsCanReceive(true);
                            }
                        }
                    }
                }
            }
        }
        builder.setRet(0);
        return builder;
    }


    /**
     * 领取排行榜奖励
     * @param serverId
     * @param userId
     * @param cityId
     */
    public static MonopolyMarketProto.MonopolyMarketFortressRankReceiveRewardRespMsg.Builder receiveRankReward(long serverId, long userId, int cityId){
        MonopolyMarketProto.MonopolyMarketFortressRankReceiveRewardRespMsg.Builder builder = MonopolyMarketProto.MonopolyMarketFortressRankReceiveRewardRespMsg.newBuilder();
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId,true);
        if(monopolyMarket == null){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        synchronized (monopolyMarket){
            String unionId = getUserBelongUnionId(monopolyMarket,"",userId);
            MonopolyMarketFortressUnionInfo unionInfo = getMonopolyMarketFortressUnionInfo(monopolyMarket,unionId,false);
            if(unionInfo == null){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_NO_CAN_RECEIVE_RANK_REWARD);
                return builder;
            }
            MonopolyMarketFortressCity city = getMonopolyMarketFortressCity(monopolyMarket,cityId,false);
            if(city == null){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_CITY_ID_NO_EXIST);
                return builder;
            }
            MonopolyMarketFortressRankData rankInfo = getRankInfo(monopolyMarket,city,unionId,false);
            if(rankInfo == null){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_NO_CAN_RECEIVE_RANK_REWARD);
                return builder;
            }
            MonopolyMarketFortressRankReward rankReward = getRankReward(cityId, rankInfo.getRank());
            if(rankReward == null){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_NO_CAN_RECEIVE_RANK_REWARD);
                return builder;
            }
            MonopolyMarketFortressUserData marketFortressUserData = getMonopolyMarketFortressUserData(monopolyMarket,userId,unionId,true);
            if(marketFortressUserData.getReceivedIdList().contains(cityId)){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_NOT_REPEAT_THE_AWARD);
                return builder;
            }
            String reward = null;
            if(unionInfo.baseInfo.getUnionBaseInfo().getMasterUserId() == userId){
                // 会长奖励
                reward = rankReward.leaderReward;
            }else {
                reward = rankReward.reward;
            }
            builder.setReward(reward);
            marketFortressUserData.getReceivedIdList().add(cityId);
            marketFortressUserData.setUpdateOption();
        }
        builder.setRet(0);
        return builder;
    }


    /**
     * 获取联盟玩家派遣信息
     * @param serverId
     * @param unionId
     * @param cityId
     * @return
     */
    public static MonopolyMarketProto.MonopolyMarketFortressGetUnionDispatchDetailRespMsg.Builder getUnionDispatchDetail(long serverId, long userId,String unionId, int cityId){
        MonopolyMarketProto.MonopolyMarketFortressGetUnionDispatchDetailRespMsg.Builder builder = MonopolyMarketProto.MonopolyMarketFortressGetUnionDispatchDetailRespMsg.newBuilder();
        MonopolyMarket monopolyMarket = MonopolyMarketMgr.getMonopolyMarket(serverId,true);
        if(monopolyMarket == null){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        synchronized (monopolyMarket){
            MonopolyMarketFortressUnionInfo unionInfo = getMonopolyMarketFortressUnionInfo(monopolyMarket,unionId,false);
            if(unionInfo == null){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_UNION_NO_EXIST);
                return builder;
            }
            if(unionInfo.baseInfo.getIsDelete()){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_NO_THIS_UNION_DISPATCH_RECORD);
                return builder;
            }
            MonopolyMarketFortressCity city = getMonopolyMarketFortressCity(monopolyMarket,cityId,false);
            if(city == null){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_NO_UNION_DISPATCH);
                return builder;
            }
            // 采集期只能查看自己联盟的派遣记录
            String userUnionId = getUserBelongUnionId(monopolyMarket,"",userId);
            if(MonopolyMarketCommonMgr.isSettlementFortress() && !userUnionId.equals(unionId)){
                builder.setRet(GameErrorCode.E_MONOPOLY_MARKET_RES_FORTRESS_THIS_TIME_NO_SELECT_OTHER_UNION_DISPATCH_RECORD);
                return builder;
            }
            Set<Long> userSet = new HashSet<>();
            for (MonopolyMarketFortressUserData item : unionInfo.memberInfoMap.values()){
                MonopolyMarketProto.MonopolyMarketFortressUnionMemberDispatchEntity.Builder memberDispatchEntity = MonopolyMarketProto.MonopolyMarketFortressUnionMemberDispatchEntity.newBuilder();
                long totalValue = getUserDispatchValue(monopolyMarket,unionId,cityId,item.getUserId());
                if(totalValue > 0){
                    memberDispatchEntity.setUserId(item.getUserId());
                    memberDispatchEntity.setTotalValue(totalValue);
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(item.getUserId());
                    if(userBaseInfo != null){
                        memberDispatchEntity.setUserName(userBaseInfo.getNickName());
                    }
                    builder.addUnionMemberList(memberDispatchEntity);
                    userSet.add(item.getUserId());
                }
            }
            // 结算期 和 采集期 也需要下发没有派遣的玩家
            if(MonopolyMarketCommonMgr.isSettlementFortress() || MonopolyMarketCommonMgr.isCollectingFortress()){
                for (long item : unionInfo.baseInfo.getMemberIdList()){
                    if(!userSet.contains(item)){
                        MonopolyMarketProto.MonopolyMarketFortressUnionMemberDispatchEntity.Builder memberDispatchEntity = MonopolyMarketProto.MonopolyMarketFortressUnionMemberDispatchEntity.newBuilder();
                        memberDispatchEntity.setUserId(item);
                        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(item);
                        if(userBaseInfo != null){
                            memberDispatchEntity.setUserName(userBaseInfo.getNickName());
                        }
                        builder.addUnionMemberList(memberDispatchEntity);
                    }
                }
            }
        }
        builder.setRet(0);
        return builder;
    }


    /**
     * 领取采集奖励
     * @param userId
     */
    public static void receiveCollectReward(long userId){
        List<MonopolyMarketProto.MonopolyMarketFortressTipEntity> fortressSettlementList = MonopolyMarketFortressMgr.receiveRewardList(userId);
        if(fortressSettlementList.size() <= 0){
            return;
        }
        // 同步给区服
        MonopolyMarketProto.MonopolyMarketEnterRespMsgToGameServerMsg.Builder builder = MonopolyMarketProto.MonopolyMarketEnterRespMsgToGameServerMsg.newBuilder();
        builder.addAllFortressSettlementList(fortressSettlementList);
        long serverId = CrossUserMgr.getServerIdByUserId(userId);
        MessageHelper.sendPacket(serverId, userId , YanQuMessageUtils.buildMessage(GameProtocol.S_MONOPOLY_MARKET_FORTRESS_RECEIVE_COLLECT_REWARD_FROM_CROSS, builder));
    }


    /**
     * 获取要塞可采集的联盟数量
     * @return
     */
    public static int getCollectUnionNum(int id){
        MonopolyMarketResConfigData configData = fortressConfigMap.get(id);
        if(configData != null && configData.collectRewardList.size() != 0){
            MonopolyMarketFortressCollectReward item = configData.collectRewardList.get(configData.collectRewardList.size() -1 );
            return item.endRank;
        }
        return 0;
    }

    /**
     * 获取要塞采集的奖励
     * @param id   要塞id
     * @param rank  排名
     * @return
     */
    public static String getCollectUnionReward(int id ,int rank){
        Property reward = new Property();
        MonopolyMarketResConfigData configData = fortressConfigMap.get(id);
        if(configData != null && configData.collectRewardList.size() != 0){
            for (MonopolyMarketFortressCollectReward item : configData.collectRewardList){
                if(item.startRank <= rank && rank <= item.endRank ){
                    int diff = ConfigMgr.getFortressCollectingPeriodEndSecond() - ConfigMgr.getFortressCollectingPeriodOpenSecond();
                    int i = diff / GameConfig.MONOPOLYMARKET_BIANGUAN_TIME;
                    reward.addProperty(GameConfig.GAME_ITEM_UNION_CONTRIBUTION, BigInteger.valueOf(item.contribution * i));
                    reward.addProperty(GameConfig.GAME_ITEM_UNION_WEALTH, BigInteger.valueOf(item.wealth * i));
                }
            }
        }
        return PropertyHelper.parsePropertyToString(reward);
    }
    /**
     * 获取联盟里玩家派遣的记录
     * @return
     */
    public static List<MonopolyMarketProto.MonopolyMarketFortressCityUserDispatchEntity> getMonopolyMarketFortressCityUserDispatchEntityList(MonopolyMarket monopolyMarket,String unionId,int cityId,long userId){
        List<MonopolyMarketProto.MonopolyMarketFortressCityUserDispatchEntity> list = new ArrayList<>();
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        if(unionInfo != null){
            // 下发该联盟的派遣信息
            for(MonopolyMarketFortressUserData member : unionInfo.memberInfoMap.values()){
                List<MonopolyMarketFortressPatronsDispatchInfo> dispatchList = member.getDispatchMap().get(cityId);
                if(dispatchList != null && dispatchList.size() > 0){
                    // 成员的派遣信息
                    MonopolyMarketProto.MonopolyMarketFortressCityUserDispatchEntity.Builder userDispatchInfo = MonopolyMarketProto.MonopolyMarketFortressCityUserDispatchEntity.newBuilder();
                    userDispatchInfo.setUserId(member.getUserId());
                    UserBaseInfo memberUserBaseInfo = CrossUserMgr.getUserBaseInfo(member.getUserId());
                    if(memberUserBaseInfo != null){
                        userDispatchInfo.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(memberUserBaseInfo));
                    }
                    for (MonopolyMarketFortressPatronsDispatchInfo patrons : dispatchList){
                        MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity.Builder patronsDispatchEntity = MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity.newBuilder();
                        patronsDispatchEntity.setPatronsId(patrons.getId());
                        patronsDispatchEntity.setValue(patrons.getEarn());
                        patronsDispatchEntity.setPlus(patrons.getPlus());
                        patronsDispatchEntity.setSkinId(patrons.getSkillId());
                        patronsDispatchEntity.setPromotionId(patrons.getpId());
                        userDispatchInfo.addPatronsList(patronsDispatchEntity);
                    }
                    list.add(userDispatchInfo.build());
                }
            }
        }
        return list;
    }

    /**
     * @param userId
     */
    public static MonopolyMarketFortressUserData getMonopolyMarketFortressUserData(MonopolyMarket monopolyMarket,long userId,String unionId,boolean newIfNull){
        int weekId =  MonopolyMarketCommonMgr.getMonopolyMarketWeekId();
        MonopolyMarketFortressUserData monopolyMarketFortressUserData = monopolyMarket.monopolyMarketFortress.userMap.get(userId);
        if(monopolyMarketFortressUserData == null && newIfNull){
            monopolyMarketFortressUserData = new MonopolyMarketFortressUserData();
            monopolyMarketFortressUserData.setInsertOption();
            monopolyMarketFortressUserData.setGroupId(monopolyMarket.group.getGroupId());
            monopolyMarketFortressUserData.setUnionId(unionId);
            monopolyMarketFortressUserData.setUserId(userId);
            monopolyMarketFortressUserData.setWeekId(weekId);
            monopolyMarket.monopolyMarketFortress.userMap.put(userId,monopolyMarketFortressUserData);
            if(!StringUtils.isNullOrEmpty(unionId)){
                MonopolyMarketFortressUnionInfo unionInfo = getMonopolyMarketFortressUnionInfo(monopolyMarket,unionId,true);
                unionInfo.memberInfoMap.put(userId,monopolyMarketFortressUserData);
            }
        }
        if(monopolyMarketFortressUserData != null && !StringUtils.isNullOrEmpty(unionId) && !unionId.equals(monopolyMarketFortressUserData.getUnionId())){
            // 联盟成员变更的情况
            monopolyMarketFortressUserData.setUnionId(unionId);
            MonopolyMarketFortressUnionInfo unionInfo = getMonopolyMarketFortressUnionInfo(monopolyMarket,unionId,true);
            unionInfo.memberInfoMap.put(userId,monopolyMarketFortressUserData);
        }
        return monopolyMarketFortressUserData;
    }

    public static List<MonopolyMarketFortressPatronsDispatchInfo> formatPatronsList(List<MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity> list){
        List<MonopolyMarketFortressPatronsDispatchInfo> patronsList = new ArrayList<>();
        for (MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity item : list){
            MonopolyMarketFortressPatronsDispatchInfo dispatchInfo = new MonopolyMarketFortressPatronsDispatchInfo();
            dispatchInfo.setId(item.getPatronsId());
            dispatchInfo.setEarn(item.getValue());
            dispatchInfo.setPlus(item.getPlus());
            dispatchInfo.setSkillId(item.getSkinId());
            dispatchInfo.setpId(item.getPromotionId());
            patronsList.add(dispatchInfo);
        }
        return patronsList;
    }

    /**
     * 刷新联盟派遣记录排名
     * @param monopolyMarket
     * @param unionId
     * @param cityId
     */
    public static void refreshRank(MonopolyMarket monopolyMarket,String unionId,int cityId,boolean newIfNullRank){
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        if(unionInfo == null){
            return;
        }
        MonopolyMarketFortressCity city = getMonopolyMarketFortressCity(monopolyMarket,cityId,true);
        MonopolyMarketFortressRankData rankInfo = getRankInfo(monopolyMarket,city,unionId,newIfNullRank);
        if(rankInfo != null){
            // 加成
            Map<Integer,Integer> plusMap = getPlusMap(monopolyMarket,unionId,cityId);
            long totalValues = 0;
            for (MonopolyMarketFortressUserData item : unionInfo.memberInfoMap.values()){
                List<MonopolyMarketFortressPatronsDispatchInfo> list = item.getDispatchMap().get(cityId);
                if(list != null){
                    for (MonopolyMarketFortressPatronsDispatchInfo dispatchInfo : list){
                        PatronsInfo patronsInfo = PatronsMgr.getPatronsInfoMap().get(dispatchInfo.getId());
                        int plus = 0;
                        if(patronsInfo != null){
                            plus = plusMap.get(patronsInfo.getOccupation());
                        }
                        totalValues += (dispatchInfo.getEarn() * (1000 + plus) / 1000);
                    }
                }
            }
            if(rankInfo.getTotalValue() != totalValues){
                if(rankInfo.getTotalValue() <= 0 && totalValues > 0){
                    city.rankList.add(rankInfo);
                }
                rankInfo.setTotalValue(totalValues);
                rankInfo.setUpdateTime(DateHelper.getCurrentSecond());
                if(rankInfo.getTotalValue() <= 0){
                    city.rankList.remove(rankInfo);
                }
            }
        }
    }

    /**
     * 获取联盟派遣的城池门客加成值
     * @param monopolyMarket
     * @param unionId
     * @param cityId
     * @return
     */
    public static Map<Integer,Integer> getPlusMap(MonopolyMarket monopolyMarket,String unionId,int cityId){
        Map<Integer,Integer> plusMap = new HashMap<>();
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        if(unionInfo != null){
            for (MonopolyMarketFortressUserData member :unionInfo.memberInfoMap.values()){
                List<MonopolyMarketFortressPatronsDispatchInfo> list = member.getDispatchMap().get(cityId);
                if(list != null){
                    for (MonopolyMarketFortressPatronsDispatchInfo dispatchInfo : list){
                        PatronsInfo patronsInfo = PatronsMgr.getPatronsInfoMap().get(dispatchInfo.getId());
                        if(patronsInfo != null){
                            plusMap.put(patronsInfo.getOccupation(), plusMap.getOrDefault(patronsInfo.getOccupation(),0) + dispatchInfo.getPlus());
                        }
                    }
                }
            }
        }
        return plusMap;
    }

    /**
     * 获取玩家在城池派遣的值
     * @return
     */
    public static long getUserDispatchValue(MonopolyMarket monopolyMarket,String unionId,int cityId,long userId){
        long totalValue = 0;
        MonopolyMarketFortressUserData userData = monopolyMarket.monopolyMarketFortress.userMap.get(userId);
        if(userData != null){
            List<MonopolyMarketFortressPatronsDispatchInfo> list = userData.getDispatchMap().get(cityId);
            if(list != null){
                Map<Integer,Integer> plusMap = getPlusMap(monopolyMarket,unionId,cityId);
                for (MonopolyMarketFortressPatronsDispatchInfo item : list){
                    totalValue += calDispatchValue(item,plusMap);
                }
            }
        }
        return totalValue;
    }

    public static long getUnionDispatchValue(MonopolyMarket monopolyMarket,String unionId,int cityId){
        long value = 0;
        MonopolyMarketFortressCity city = monopolyMarket.monopolyMarketFortress.cityMap.get(cityId);
        if(city != null){
            MonopolyMarketFortressRankData rankData = city.rankMap.get(unionId);
            if(rankData != null){
                value = rankData.getTotalValue();
            }
        }
        return value;
    }

    /**
     * 获取该联盟派遣该城池的成员数量
     * @param monopolyMarket
     * @param unionId
     * @param cityId
     * @return
     */
    public static int getDispatchNum(MonopolyMarket monopolyMarket,String unionId,int cityId){
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        int dispatchNum = 0;
        if(unionInfo != null){
            for (MonopolyMarketFortressUserData item : unionInfo.memberInfoMap.values()){
                List<MonopolyMarketFortressPatronsDispatchInfo> list = item.getDispatchMap().get(cityId);
                if(list != null && list.size() > 0){
                    dispatchNum++;
                }
            }
        }
        return dispatchNum;
    }

    /**
     * 获取参赛联盟的总人数
     */
    public static int getUnionMemberNum(MonopolyMarket monopolyMarket,String unionId){
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        int num = 0;
        if(unionInfo != null){
            num = unionInfo.baseInfo.getMemberIdList().size();
        }
        return num;
    }


    public static MonopolyMarketFortressCity getMonopolyMarketFortressCity(MonopolyMarket monopolyMarket,int cityId,boolean newIfNull){
        MonopolyMarketFortressCity city = monopolyMarket.monopolyMarketFortress.cityMap.get(cityId);
        if(city == null && newIfNull){
            city = new MonopolyMarketFortressCity(cityId);
            monopolyMarket.monopolyMarketFortress.cityMap.put(cityId,city);
        }
        return city;
    }

    /**
     * 计算派遣门客的数值
     * @return
     */
    public static long calDispatchValue(MonopolyMarketFortressPatronsDispatchInfo dispatchInfo, Map<Integer,Integer> plusMap){
        PatronsInfo patronsInfo = PatronsMgr.getPatronsInfoMap().get(dispatchInfo.getId());
        int plus = 0;
        if(patronsInfo != null){
            plus = plusMap.get(patronsInfo.getOccupation());
        }
        return (dispatchInfo.getEarn() * (1000 + plus) )/ 1000;
    }

    /**
     * 获取玩家要塞派遣的门客
     * @param monopolyMarket
     * @param userId
     * @return
     */
    public static List<MonopolyMarketProto.MonopolyMarketFortressDispatchEntity> getMonopolyMarketFortressUserDispatchList(MonopolyMarket monopolyMarket, long userId){
        List<MonopolyMarketProto.MonopolyMarketFortressDispatchEntity> list = new ArrayList<>();
        MonopolyMarketFortressUserData fortressUserData = monopolyMarket.monopolyMarketFortress.userMap.get(userId);
        if(fortressUserData != null){
            for(Map.Entry<Integer, List<MonopolyMarketFortressPatronsDispatchInfo>> entry : fortressUserData.getDispatchMap().entrySet()){
                int fortressId = entry.getKey();
                for (MonopolyMarketFortressPatronsDispatchInfo item : entry.getValue()){
                    list.add(MonopolyMarketProto.MonopolyMarketFortressDispatchEntity.newBuilder().setFortressId(fortressId).setPatronsId(item.getId()).build());
                }
            }
        }
        return list;
    }

    /**
     * @param monopolyMarket
     * @param unionId
     */
    public static MonopolyMarketFortressUnionInfo getMonopolyMarketFortressUnionInfo(MonopolyMarket monopolyMarket,String unionId,boolean newIfNull){
        MonopolyMarketFortressUnionInfo fortressUnionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        if(fortressUnionInfo == null && newIfNull){
            MonopolyMarketFortressUnionData baseData = new MonopolyMarketFortressUnionData();
            baseData.setInsertOption();
            baseData.setGroupId(monopolyMarket.group.getGroupId());
            baseData.setUnionId(unionId);
            baseData.setUnionBaseInfo(new UnionBaseInfo());
            baseData.setWeekId(MonopolyMarketCommonMgr.getMonopolyMarketWeekId());
            fortressUnionInfo = new MonopolyMarketFortressUnionInfo(baseData);
            monopolyMarket.monopolyMarketFortress.unionMap.put(unionId,fortressUnionInfo);
        }
        return fortressUnionInfo;
    }

    /**
     * 刷新要塞 （采集期解散 结算所有可采集的玩家奖励 并通知 在线的玩家领奖）
     */
    public static boolean refreshMonopolyMarketFortress(MonopolyMarket monopolyMarket,int time){
        int oldRefreshTime = monopolyMarket.group.getFortressRefreshTime();
        // 派遣期结算排序
        int refreshTime = DateHelper.getWeekBeginTimestamp(oldRefreshTime) + ConfigMgr.getFortressDispatchPeriodEndSecond();
        if(time >= refreshTime && oldRefreshTime < refreshTime ){
            // 排序
            refreshFortressRank(monopolyMarket,true);
            monopolyMarket.group.setFortressRefreshTime(time);
        }
        // 采集期计算时间
        refreshTime = DateHelper.getWeekBeginTimestamp(oldRefreshTime) + ConfigMgr.getFortressCollectingPeriodEndSecond();
        if(time >= refreshTime && oldRefreshTime < refreshTime){
            // 结算 采集奖励
            for(MonopolyMarketFortressCity item : monopolyMarket.monopolyMarketFortress.cityMap.values()){
                int collectUnionNum = getCollectUnionNum(item.id);
                for (MonopolyMarketFortressRankData rankInfo : item.rankList){
                    MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(rankInfo.getUnionId());
                    if(unionInfo == null ){
                        continue;
                    }
                    if(collectUnionNum-- <= 0){
                        break;
                    }
                    String reward = getCollectUnionReward(item.id, rankInfo.getRank());
                    for (long memberId : unionInfo.baseInfo.getMemberIdList()){
                        saveMonopolyMarketFortressRewardData(item.id,rankInfo.getRank(),unionInfo.baseInfo.getUnionBaseInfo().getUnionName(),memberId,rankInfo.getWeekId(),reward);
                    }
                }
            }
            // 清空所有城池派遣和排行榜
            monopolyMarket.monopolyMarketFortress.userMap.clear();
            monopolyMarket.monopolyMarketFortress.unionMap.clear();
            monopolyMarket.monopolyMarketFortress.cityMap.clear();
            monopolyMarket.group.setFortressRefreshTime(time);
            return true;
        }
        return false;
    }

    /**
     * 解散联盟
     * @param monopolyMarket
     * @param unionId
     */
    public static void deleteUnion(MonopolyMarket monopolyMarket,String unionId){
        if(!MonopolyMarketCommonMgr.isDispatchFortress()){
            return;
        }
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        if(unionInfo == null){
            return;
        }
        for (MonopolyMarketFortressUserData item : unionInfo.memberInfoMap.values()){
            clearUserDispatch(item);
            item.setUnionId("");
        }
        unionInfo.memberInfoMap.clear();
        unionInfo.baseInfo.setIsDelete(true);
        for (MonopolyMarketFortressCity city : monopolyMarket.monopolyMarketFortress.cityMap.values()){
            MonopolyMarketFortressRankData rankInfo = city.rankMap.get(unionId);
            if(rankInfo != null){
                rankInfo.setTotalValue(0);
                rankInfo.setUpdateTime(DateHelper.getCurrentSecond());
                rankInfo.setRank(-1);
                city.rankList.remove(rankInfo);
            }
        }
    }

    /**
     * 玩家离开联盟
     * @param monopolyMarket
     * @param unionId
     * @param userId
     */
    public static void leaveUnion(MonopolyMarket monopolyMarket,String unionId,long userId){
        if(!MonopolyMarketCommonMgr.isDispatchFortress()){
            return;
        }
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        if(unionInfo == null){
            return;
        }
        MonopolyMarketFortressUserData userData = unionInfo.memberInfoMap.remove(userId);
        if(userData == null){
            return;
        }
        Set<Integer> cityList = new HashSet<>(userData.getDispatchMap().keySet());
        clearUserDispatch(userData);
        userData.setUnionId("");
        unionInfo.memberInfoMap.remove(userId);
        // 重新计算玩家派遣过的要塞的联盟分数
        for (int item : cityList){
            MonopolyMarketFortressMgr.refreshRank(monopolyMarket,unionId,item,false);
        }
    }

    /**
     * 清空玩家派遣
     * @param userData
     */
    public static void clearUserDispatch(MonopolyMarketFortressUserData userData){
        userData.getDispatchMap().clear();
        userData.dispatchCityMap.clear();
        userData.setUpdateOption();
    }

    /**
     * 锁定联盟信息
     * @param lockUnionList
     */
    public static void lockUnionInfo(MonopolyMarket monopolyMarket, long serverId, List<MonopolyMarketProto.MonopolyMarketFortressLockUnionInfoEntity> lockUnionList){
        for (MonopolyMarketProto.MonopolyMarketFortressLockUnionInfoEntity item : lockUnionList){
            MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(item.getUnionId());
            if(unionInfo == null){
                continue;
            }
            // 有可能在定时器上来之前卡点 退盟了，上来的数据没有他，但是他又有派遣 ，那就给他加一个锁定名额
            for (MonopolyMarketFortressUserData member : unionInfo.memberInfoMap.values()){
                if(!item.getMemberListList().contains(member.getUserId())){
                    item.getMemberListList().add(member.getUserId());
                }
            }
            unionInfo.baseInfo.setMemberIdList(item.getMemberListList());
            unionInfo.baseInfo.setUnionBaseInfo(UnionBasePb.parseUnionBaseInfo(item.getUnionInfo()));
        }
        // 反馈给区服同步成功
        MessageHelper.sendPacket(serverId, 0 , YanQuMessageUtils.buildMessage(GameProtocol.S_MONOPOLY_MARKET_FORTRESS_LOCK_UNION_SUCCESS_FROM_CROSS));
    }

    /**
     * 修改联盟名称
     * @param monopolyMarket
     * @param unionId
     * @param unionName
     */
    public static void changeUnionName(MonopolyMarket monopolyMarket, String unionId, String unionName){
        if(!MonopolyMarketCommonMgr.isDispatchFortress()){
            return;
        }
        MonopolyMarketFortressUnionInfo unionInfo = monopolyMarket.monopolyMarketFortress.unionMap.get(unionId);
        if(unionInfo == null){
            return;
        }
        if(!unionInfo.baseInfo.getUnionBaseInfo().getUnionName().equals(unionName)){
            unionInfo.baseInfo.getUnionBaseInfo().setUnionName(unionName);
        }
    }

    /**
     * 获取本轮 玩家代表出战的联盟id
     * @return
     */
    public static String getUserBelongUnionId(MonopolyMarket monopolyMarket,String unionId, long userId){
        if(MonopolyMarketCommonMgr.isDispatchFortress()){
            return unionId;
        }else if(MonopolyMarketCommonMgr.isSettlementFortress() || MonopolyMarketCommonMgr.isCollectingFortress()){
            // 优先去取玩家身上的联盟 因为有可能锁定后的联盟成员 没有该成员 但是他又派遣了
            MonopolyMarketFortressUserData userData = getMonopolyMarketFortressUserData(monopolyMarket,userId,"",false);
            if(userData != null && !StringUtils.isNullOrEmpty(userData.getUnionId())){
                return userData.getUnionId();
            }
            for(MonopolyMarketFortressUnionInfo unionInfo : monopolyMarket.monopolyMarketFortress.unionMap.values()){
                if(unionInfo.baseInfo.getMemberIdList().contains(userId)){
                    return unionInfo.baseInfo.getUnionId();
                }
            }
        }
        return "";
    }

    /**
     * 刷新所有城池排行榜
     * @param monopolyMarket
     */
    public static void refreshFortressRank(MonopolyMarket monopolyMarket,boolean addLog){
        int now = DateHelper.getCurrentSecond();
        for(MonopolyMarketFortressCity city : monopolyMarket.monopolyMarketFortress.cityMap.values()){
            sortMonopolyMarketFortressCity(city);
            int rank = 1;
            for (MonopolyMarketFortressRankData item : city.rankList){
                item.setRank(rank++);
                if(addLog){
                    MonopolyMarketLogMgr.addMonopolyMarketFortressSettlementLogData(new MonopolyMarketFortressSettlementLogData(monopolyMarket.group.getGroupId(),MonopolyMarketCommonMgr.getMonopolyMarketWeekId(),item.getFortressId(),item.getUnionId(),item.getTotalValue(),item.getRank(),now));
                }
            }
        }
    }

    public static void sortMonopolyMarketFortressCity(MonopolyMarketFortressCity city){
        city.rankList.sort((t1,t2)->{
            if(t1.getTotalValue() != t2.getTotalValue()){
                return Long.compare(t2.getTotalValue(),t1.getTotalValue());
            }else if(t1.getUpdateTime() != t2.getUpdateTime()){
                return Integer.compare(t1.getUpdateTime(),t2.getUpdateTime());
            }else {
                return 0;
            }
        });
    }


    public static MonopolyMarketFortressRankData getRankInfo(MonopolyMarket monopolyMarket,MonopolyMarketFortressCity city,String unionId,boolean newIfNullRank){
        MonopolyMarketFortressRankData rankInfo = city.rankMap.get(unionId);
        if(rankInfo == null && newIfNullRank){
            rankInfo = new MonopolyMarketFortressRankData();
            rankInfo.setInsertOption();
            rankInfo.setWeekId(MonopolyMarketCommonMgr.getMonopolyMarketWeekId());
            rankInfo.setFortressId(city.id);
            rankInfo.setGroupId(monopolyMarket.group.getGroupId());
            rankInfo.setUnionId(unionId);
            city.rankMap.put(unionId, rankInfo);
        }
        return rankInfo;
    }

    /**
     * 是有有排行奖励
     * @param cityId
     * @param rank
     * @return
     */
    private static MonopolyMarketFortressRankReward getRankReward(int cityId, int rank){
        MonopolyMarketResConfigData configData = fortressConfigMap.get(cityId);
        if(configData != null){
            List<MonopolyMarketFortressRankReward> list = ConfigMgr.getFortressRankRewardMap().get(configData.getLevel());
            if(list != null){
                for (MonopolyMarketFortressRankReward item : list){
                    if(item.startRank <= rank && rank <= item.endRank){
                        return item;
                    }
                }
            }
        }
        return null;
    }

    /**
     * @param cityId
     * @return
     */
    private static int getMaxRankReward(int cityId){
        MonopolyMarketResConfigData configData = fortressConfigMap.get(cityId);
        if(configData != null){
            List<MonopolyMarketFortressRankReward> list = ConfigMgr.getFortressRankRewardMap().get(configData.getLevel());
            if(list != null){
                MonopolyMarketFortressRankReward rankReward = list.get(list.size() - 1);
                if(rankReward != null){
                    return rankReward.endRank;
                }
            }
        }
        return 0;
    }


    /**
     * 领取要塞采集结算奖励
     * @param userId
     * @return
     */
    public static List<MonopolyMarketProto.MonopolyMarketFortressTipEntity> receiveRewardList(long userId){
        List<MonopolyMarketProto.MonopolyMarketFortressTipEntity> fortressSettlementList = new ArrayList<>();
        List<MonopolyMarketFortressRewardData> list = userRewardMap.get(userId);
        if(list != null && list.size() > 0){
            List<MonopolyMarketFortressRewardData> tempList = new ArrayList<>();
            synchronized (list) {
                tempList.addAll(list);
                list.clear();
            }
            for (MonopolyMarketFortressRewardData item : tempList){
                MonopolyMarketProto.MonopolyMarketFortressTipEntity.Builder settlement = MonopolyMarketProto.MonopolyMarketFortressTipEntity.newBuilder();
                settlement.setId(item.getFortressId());
                settlement.setUnionName(item.getUnionName());
                settlement.setRank(item.getRank());
                settlement.setReward(item.getReward());
                item.setIdReceive(true);
                fortressSettlementList.add(settlement.build());
            }
            // 入库
            synchronized (tempRewardFinishList){
                tempRewardFinishList.addAll(tempList);
            }
        }
        return fortressSettlementList;
    }

    public static void synFortressPatrons(MonopolyMarket monopolyMarket,long userId, List<MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity> list){
        MonopolyMarketFortressUserData userData = monopolyMarket.monopolyMarketFortress.userMap.get(userId);
        if(userData != null && !StringUtils.isNullOrEmpty(userData.getUnionId())){
            Set<Integer> needRefreshRank = new HashSet<>();
            for (MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity item : list){
                int cityId = userData.dispatchCityMap.getOrDefault(item.getPatronsId(),0);
                List<MonopolyMarketFortressPatronsDispatchInfo> dispatchInfoList = userData.getDispatchMap().get(cityId);
                if(dispatchInfoList != null){
                    for (MonopolyMarketFortressPatronsDispatchInfo dispatchInfo : dispatchInfoList){
                        if(dispatchInfo.getId() == item.getPatronsId()){
                            if(cloneMonopolyMarketFortressPatronsDispatchInfo(dispatchInfo,item)){
                                needRefreshRank.add(cityId);
                                userData.setUpdateOption();
                            }
                            break;
                        }
                    }
                }
            }
            needRefreshRank.forEach(e->{
                refreshRank(monopolyMarket,userData.getUnionId(),e,false);
            });
        }
    }

    private static boolean cloneMonopolyMarketFortressPatronsDispatchInfo(MonopolyMarketFortressPatronsDispatchInfo dispatchInfo, MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity dispatchEntity){
        boolean valueChange = false;
        if(dispatchInfo.getEarn() != dispatchEntity.getValue()){
            dispatchInfo.setEarn(dispatchEntity.getValue());
            valueChange = true;
        }
        if(dispatchInfo.getPlus() != dispatchEntity.getPlus()){
            dispatchInfo.setPlus(dispatchEntity.getPlus());
            valueChange = true;
        }
        if(dispatchInfo.getSkillId() != dispatchEntity.getSkinId()){
            dispatchInfo.setSkillId(dispatchEntity.getSkinId());
        }
        if(dispatchInfo.getpId() != dispatchEntity.getPromotionId()){
            dispatchInfo.setpId(dispatchEntity.getPromotionId());
        }
        return valueChange;
    }

    /**
     * 检查上轮是否正常结束 如果没有 补发采集奖励
     * @param monopolyMarket
     */
    private static void checkNormalSettlement(MonopolyMarket monopolyMarket){
        // 判断  刷新时间是否 小于上一轮的采集期结束时间
        // 如果是 说明上一轮没有被正常结算  再判断刷新是否小于 上一轮的结算期开始时间
        // 如果是 说明 上一轮 有结算期 但是没有被正常结算
        int now = DateHelper.getCurrentSecond();
        if(monopolyMarket.group.getFortressRefreshTime() == 0){
            // 版本迭代需要 3.9->4.0  不能移除 因为存在fortressRefreshTime = 0
            monopolyMarket.group.setFortressRefreshTime(now);
            return;
        }
        if(monopolyMarket.group.getChangTime() > MonopolyMarketCommonMgr.getLastRoundFortressDispatchStartTime(now)){
            // 分组变更的时间 大于 上一轮派遣期的开始时间 算结算了
            return;
        }
        int thisWeekCollectEndTime = MonopolyMarketCommonMgr.getLastRoundFortressCollectEndTime(now);
        if(monopolyMarket.group.getFortressRefreshTime() >= thisWeekCollectEndTime){
            return;
        }
        int thisWeekSettlementEndTime = MonopolyMarketCommonMgr.getLastRoundFortressSettlementStartTime(now);
        if(monopolyMarket.group.getFortressRefreshTime() < thisWeekSettlementEndTime){
            return;
        }
        // 结算上一轮时间
        int lastRoundWeekId = MonopolyMarketCommonMgr.getMonopolyMarketWeekId(thisWeekSettlementEndTime);
        List<MonopolyMarketFortressRankData> rankList = MonopolyMarketBussiness.getMonopolyMarketFortressRankData(monopolyMarket.group.getGroupId(), lastRoundWeekId);
        if(rankList.size() <= 0){
            return;
        }
        Map<String, MonopolyMarketFortressUnionData> unionDataMap = new HashMap();
        List<MonopolyMarketFortressUnionData> unionList = MonopolyMarketBussiness.getMonopolyMarketFortressUnionDataList(monopolyMarket.group.getGroupId(), lastRoundWeekId);
        for (MonopolyMarketFortressUnionData item : unionList){
            unionDataMap.put(item.getUnionId(),item);
        }
        for (MonopolyMarketFortressRankData item : rankList) {
            int collectUnionNum = getCollectUnionNum(item.getFortressId());
            MonopolyMarketFortressUnionData unionData = unionDataMap.get(item.getUnionId());
            if (unionData == null) {
                continue;
            }
            if(item.getRank() == -1 || item.getRank() > collectUnionNum){
                continue;
            }
            String reward = getCollectUnionReward(item.getFortressId(), item.getRank());
            for (long memberId : unionData.getMemberIdList()) {
                saveMonopolyMarketFortressRewardData(item.getFortressId(),item.getRank(),unionData.getUnionBaseInfo().getUnionName(),memberId,item.getWeekId(),reward);
            }
        }
        monopolyMarket.group.setFortressRefreshTime(thisWeekCollectEndTime);
    }


    public static void saveMonopolyMarketFortressRewardData(int cityId,int rank,String unionName,long userId,int weekId,String reward){
        MonopolyMarketFortressRewardData rewardData = new MonopolyMarketFortressRewardData();
        rewardData.setInsertOption();
        rewardData.setFortressId(cityId);
        rewardData.setRank(rank);
        rewardData.setUnionName(unionName);
        rewardData.setUserId(userId);
        rewardData.setWeekId(weekId);
        rewardData.setReward(reward);

        List<MonopolyMarketFortressRewardData> list = MonopolyMarketFortressMgr.userRewardMap.get(userId);
        if (list == null) {
            list = new ArrayList<>();
            MonopolyMarketFortressMgr.userRewardMap.put(userId, list);
        }
        list.add(rewardData);
        synchronized (tempRewardFinishList) {
            tempRewardFinishList.add(rewardData);
        }
    }

    /**
     *  重置要塞
     */
    public static void resetFortress(MonopolyMarket monopolyMarket){
        // 清空玩家的派遣
        // 清空分数
        // 清空累计派遣记录
        for (MonopolyMarketFortressCity item : monopolyMarket.monopolyMarketFortress.cityMap.values()){
            for (MonopolyMarketFortressRankData rankData : item.rankMap.values()){
                rankData.setTotalValue(0);
                rankData.setUpdateTime(DateHelper.getCurrentSecond());
            }
            item.rankList.clear();
        }
        // 清空玩家派遣记录
        for (MonopolyMarketFortressUserData item : monopolyMarket.monopolyMarketFortress.userMap.values()){
            item.getDispatchMap().clear();
            item.dispatchCityMap.clear();
            item.setUpdateOption();
        }

        monopolyMarket.monopolyMarketFortress.userMap.clear();
        monopolyMarket.monopolyMarketFortress.unionMap.clear();
        monopolyMarket.monopolyMarketFortress.cityMap.clear();

        monopolyMarket.group.setFortressRefreshTime(DateHelper.getCurrentSecond());
    }

}
